package com.xh.bussiness.permission.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xh.bussiness.permission.bean.dto.RoleDto;
import com.xh.bussiness.permission.bean.request.RoleRequest;
import com.xh.bussiness.permission.dao.RoleMapper;
import com.xh.bussiness.permission.model.Role;
import com.xh.bussiness.permission.service.IRoleService;
import com.xh.core.bean.XhPage;
import com.xh.core.service.impl.BaseServiceImpl;
import com.xh.core.util.StringUtils;
import org.springframework.stereotype.Service;

import java.util.List;


@Service
public class RoleServiceImpl extends BaseServiceImpl<RoleMapper, Role> implements IRoleService {


    @Override
    public XhPage queryRolePage(XhPage page, RoleRequest bean) {
        QueryWrapper qw = new QueryWrapper<Role>();
        //拼装条件
        qw = prepareParams(bean, qw);

        return (XhPage) this.dao.selectPage(page, qw);
    }


    @Override
    public List queryRole(RoleRequest bean) {
        QueryWrapper qw = new QueryWrapper<Role>();
        //拼装条件
        qw = prepareParams(bean, qw);

        return this.selectList(qw, RoleDto.class);
    }


    @Override
    public String addRole(RoleRequest bean) {
        Role role = new Role();

        role.setName(bean.getName());
        role.setIsSystem(bean.getIsSystem());
        role.setThirdRoleId(bean.getId());
        this.insert(role);

        return null;
    }


    @Override
    public String modifyRole(RoleRequest bean) {
        Role role = this.getById(bean.getId());
        if (role == null) {
            return "当前角色id不存在";
        }

        role.setName(bean.getName());
        role.setIsSystem(bean.getIsSystem());
        if (bean.getStatus() != null) {
            role.setStatus(bean.getStatus());
        }
        this.update(role);

        return null;
    }


    @Override
    public String deleteRole(String id) {
        Role role = this.getById(id);
        if (role == null) {
            return "此角色id不存在";
        }
        role.deleteById(id);

        return null;
    }

    @Override
    public Role queryByThirdId(String lwRoleId) {
        QueryWrapper qw = new QueryWrapper();
        qw.eq("third_role_id", lwRoleId);
        Role role = this.dao.selectOne(qw);
        return role;
    }

    /**
     * 准备条件
     *
     * @param bean
     * @param qw
     */
    private QueryWrapper prepareParams(RoleRequest bean, QueryWrapper qw) {
        // 馨博不想看到“机构配置员” 这个角色
        qw.ne("name", "配置员");
        if (bean.getIds() != null && bean.getIds().length > 0) {
            qw.in("id", bean.getIds());
        }
        if (!StringUtils.isEmpty(bean.getName())) {
            qw.like("name", bean.getName());
        }
        qw.orderByDesc("modify_time");
        return qw;
    }
}
